﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Utility.Model;
using MsgCenter.BLL;
using System.Web;
using System.Web.Security;
using Utility;
using Utility.Config;

namespace BaseUI
{
    public class UserSessionService
    {
        private static IDictionary<string, UserSession> _dic = null;
        static object locker = new object();//添加一个对象作为锁
        private static IDictionary<string, UserSession> CachedDic
        {
            get
            {
                if (_dic == null)
                {
                    lock (locker)
                    {
                        if (_dic == null)
                        {
                            _dic = new Dictionary<string, UserSession>();
                        }
                    }
                }

                return _dic;
            }
        }
        /// <summary>
        /// 在哈希表中获取用户信息
        /// </summary>
        /// <param name="strAccount"></param>
        /// <returns></returns>
        public static UserSession GetUserInfo(string strAccount, string strIP)
        {
            if (string.IsNullOrEmpty(strAccount))
            {
                return null;
            }
            UserSession objUser = null;
            if (CachedDic.ContainsKey(strAccount.ToLower()))
            {
                objUser = CachedDic[strAccount.ToLower()];
            }
            else
            {
                objUser = GetUserSession(strAccount, strIP);
                if (objUser != null)
                {
                    SetUserInfo(strAccount, objUser);
                }
                return objUser;
            }
            return objUser;
        }
        /// <summary>
        /// 用户在登录页面登录成功后，调用该方法
        /// </summary>
        /// <param name="strAccount"></param>
        public static void SetUserInfo(string strAccount, UserSession objUser)
        {
            if (!string.IsNullOrEmpty(strAccount))
            {
                lock (locker)//锁
                {
                    if (CachedDic.ContainsKey(strAccount.ToLower()))
                    {
                        CachedDic.Remove(strAccount.ToLower());
                    }
                    //保存到哈希表中
                    CachedDic.Add(strAccount.ToLower(), objUser);
                }
            }
        }
        /// <summary>
        /// 移出用户信息
        /// </summary>
        /// <param name="strAccount"></param>
        public static void RemoveUserInfo(string strAccount)
        {
            //如何哈希表中有用户信息，则移除，这样可以在登录的时候实时的更新用户的基本信息。
            if (!string.IsNullOrEmpty(strAccount))
            {
                if (CachedDic.ContainsKey(strAccount.ToLower()))
                {
                    CachedDic.Remove(strAccount.ToLower());
                }
            }
        }
        /// <summary>
        /// 通过登录名获取UserSession信息
        /// </summary>
        /// <param name="strAccount"></param>
        /// <returns></returns>
        public static UserSession GetUserSession(string strAccount, string strIP)
        {
            UserSession objUser;
            Sys_User model =  BLLServiceHelper.GetUserService().GetLogin(strAccount);
            if (model != null)
            {
                if (model.UserName.ToEquals(ConfigHelper.strAdmin_UserName))
                {
                    model.IsAdmin = true;
                }
                objUser = new UserSession();
                objUser.UserID = model.UserID;
                objUser.IsAdmin = model.IsAdmin.Value;
                objUser.UserOperate = BLLServiceHelper.GetUserService().GetLoginUserOperate(model.UserID, objUser.IsAdmin);
                objUser.UserModule = BLLServiceHelper.GetUserService().GetLoginUserModule(model.UserID, objUser.IsAdmin);
                objUser.UserRoles = BLLServiceHelper.GetUserService().GetLoginUserRoles(model.UserID);
                objUser.Account = model.UserName.ToLower();
                objUser.Name = model.Name;
                Sys_Dept modelDept = BLLServiceHelper.GetDeptService().GetModel(model.DeptGuID);
                if (modelDept != null)
                {
                    objUser.DepartmentID = modelDept.ID;
                    objUser.DepartmentCode = modelDept.DeptCode;
                    objUser.DepartmentName = modelDept.DeptName;
                    Sys_Dept modelParentDept = BLLServiceHelper.GetDeptService().GetModel(Sys_Dept._.DeptID == modelDept.ParentID);
                    if (modelParentDept != null)
                    {
                        objUser.ParentOrgCode = modelParentDept.DeptCode;
                        objUser.ParentOrgID = modelParentDept.ID;
                        objUser.ParentOrgName = modelParentDept.DeptName;
                    }
                    else
                    {
                        objUser.ParentOrgID = modelDept.ID;
                        objUser.ParentOrgCode = modelDept.DeptCode;
                        objUser.ParentOrgName = modelDept.DeptName;
                    }
                }
                return objUser;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 获取登陆名,Cookie
        /// </summary>
        /// <param name="httpCont"></param>
        /// <returns></returns>
        public static string GetLoginName(System.Web.HttpContext httpCont)
        {
            HttpCookie ticketCookie = httpCont.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (ticketCookie != null)
            {
                if (!string.IsNullOrEmpty(ticketCookie.Value))
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(ticketCookie.Value);
                    if (ticket != null)
                    {
                        return ticket.Name;
                    }
                }
            }
            return string.Empty;
        }
        /// <summary>
        /// 写登陆的Cookie
        /// </summary>
        /// <param name="httpCont"></param>
        public static void SetSsoCookie(System.Web.HttpContext httpCont)
        {
            HttpCookie ticketCookie = httpCont.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (ticketCookie != null)
            {
                if (!string.IsNullOrEmpty(ticketCookie.Value))
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(ticketCookie.Value);
                    if (ticket != null)
                    {
                        FormsAuthentication.SetAuthCookie(ticket.Name, false);
                        HttpCookie cookie = FormsAuthentication.GetAuthCookie(ticket.Name, false);
                        FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(cookie.Value);
                        FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(1,
                        oldTicket.Name,
                        oldTicket.IssueDate,
                        DateTime.Now.AddMinutes(30),
                        oldTicket.IsPersistent,
                        oldTicket.UserData,
                        FormsAuthentication.FormsCookiePath);
                        cookie.Domain = Utility.Config.ConfigHelper.WebDomain;
                        cookie.Value = FormsAuthentication.Encrypt(newTicket);
                        //更新 cookie
                        HttpContext.Current.Response.SetCookie(cookie);
                    }
                }
            }
        }

        public static void DeleteSsoCookie(System.Web.HttpContext httpCont)
        {
            HttpCookie cookie = httpCont.Response.Cookies[FormsAuthentication.FormsCookieName];
            cookie.Domain = Utility.Config.ConfigHelper.WebDomain;
            cookie.Value = null;
            cookie.Expires = DateTime.Now.AddDays(-1);
            //更新cookie
            httpCont.Response.SetCookie(cookie);
        }
    }
}
